package flextv.main.command {

import com.adobe.cairngorm.commands.ICommand;
import com.adobe.cairngorm.control.CairngormEvent;

import flash.filesystem.File;

import flextv.core.logic.CoreModel;
import flextv.core.logic.Logger;
import flextv.core.vo.Playlist;
import flextv.core.vo.StoredItem;
import flextv.main.event.DeletePlaylistEvent;
import flextv.main.logic.AirUtil;
import flextv.main.logic.MainServices;

import mx.logging.ILogger;

public class DeletePlaylistCommand implements ICommand {
	
	private static const LOG: ILogger = Logger.getLog(DeletePlaylistCommand);
	
	public function DeletePlaylistCommand() {
	}

	public function execute(_event: CairngormEvent): void {
		const event: DeletePlaylistEvent = _event as DeletePlaylistEvent;
		LOG.info("Executing [event=" + event + "].");
		
		const p: Playlist = event.playlist;
		
		
		if(CoreModel.instance.currentPlaylist == p) {
			CoreModel.instance.currentPlaylist = null;
		}
		
		const playlistIndex: int = CoreModel.instance.playlists.getItemIndex(p);
		CoreModel.instance.playlists.removeItemAt(playlistIndex);
		
		
		MainServices.instance.persistenceService.deletePlaylist(p);
		
		
		for each(var item: StoredItem in p.storedItems) {
			if(CoreModel.instance.currentStoredItem == item) {
				LOG.debug("CoreModel.instance.currentStoredItem = null");
				CoreModel.instance.currentStoredItem = null;
			}
			
			const flvFile: File = AirUtil.resolveFlvFile(item.yid);
			if(flvFile.exists == true) {
				LOG.debug("Deleting flv file at ["+flvFile.nativePath+"].");
				flvFile.deleteFile();
			}
		}
	}
	
}
}